package be.jprojects.subscription.logic;

import java.util.List;

import be.jprojects.subscription.controllers.ListenersController;
import be.jprojects.subscription.dataaccess.DataAccessObjectFactory;
import be.jprojects.subscription.gui.listeners.SelectedPersonChangeListener;
import be.jprojects.subscription.logic.interfaces.ICity;
import be.jprojects.subscription.logic.interfaces.ICountry;
import be.jprojects.subscription.logic.interfaces.IPerson;
import be.jprojects.subscription.logic.interfaces.IProvince;

public class BusinessLogicController implements SelectedPersonChangeListener {
	private static BusinessLogicController instance;
	private List<IPerson> persons;
	private List<ICountry> countries;
	private IPerson selectedPerson;
	private DataAccessObjectFactory dataAccessObjectFactory;
	
	
	private BusinessLogicController() throws Exception {
		dataAccessObjectFactory = DataAccessObjectFactory.getImplementation();
		ListenersController.getInstance().addSelectedPersonChangeListener(this);
	}


	public List<IPerson> getPersons() throws Exception {
		if (persons == null)
			persons = dataAccessObjectFactory.getPersonDataAccess().getPersons();
		return persons;
	}
	
	public List<ICountry> getCountries() throws Exception {
		if (countries == null)
			countries = dataAccessObjectFactory.getCountryDataAccess().getCountries();
		return countries;
	}
	
	public void loadProvinces(ICountry country) throws Exception {
		dataAccessObjectFactory.getProvinceDataAccess().loadProvinces(country);
	}
	public void loadCities(IProvince province) throws Exception {
		dataAccessObjectFactory.getCityDataAccess().loadCities(province);
	}
	public void loadStreets(ICity city) throws Exception {
		dataAccessObjectFactory.getStreetDataAccess().loadStreets(city);
	}
	
	public void saveOrUpdatePerson(String firstName, String lastName, String middleName) throws Exception {
		if (selectedPerson == null) {
			selectedPerson = new Person();
			selectedPerson.setFirstName(firstName);
			selectedPerson.setLastName(lastName);
			selectedPerson.setMiddleName(middleName);
			dataAccessObjectFactory.getPersonDataAccess().insertPerson(selectedPerson);
			persons = null;
		} else {
			selectedPerson.setFirstName(firstName);
			selectedPerson.setLastName(lastName);
			selectedPerson.setMiddleName(middleName);
			dataAccessObjectFactory.getPersonDataAccess().updatePerson(selectedPerson);
		}
	}



	public static BusinessLogicController getInstance() throws Exception {
		if (instance == null)
			instance = new BusinessLogicController();
		return instance;
	}


	@Override
	public void selectedPersonChanged(IPerson person) {
		selectedPerson = person;
	}
	
	
}
